package org.particlethink.service.reconciliation;

import kotlin.Pair;
import org.particlethink.dto.BillStatusAndCount;
import org.particlethink.entry.BillStatus;
import org.particlethink.entry.OrderStatus;
import org.particlethink.exception.NoPermissionException;
import org.particlethink.exception.StatusException;
import org.particlethink.model.Bill;
import org.particlethink.request.ReasonRequest;
import org.particlethink.response.BillStatusCountResponse;
import org.particlethink.response.OrderStatusCountResponse;
import org.particlethink.utils.ListUtilsKt;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("SupplierUserImpl")
public class SupplierUserImpl extends Base {//企业用户

    //    对账列表（状态）
//    异议对账结果
    public void objectionBill(List<Integer> supplierIds, int billID, ReasonRequest reason) {
        Bill bill = this.billMapper.selectByPrimaryKey(billID);
        if (!bill.canObjection()) {
            throw new StatusException();
        }
        if (!supplierIds.contains(bill.getSupplierId())) {
            throw new NoPermissionException();
        }


        bill.setStatus(BillStatus.Objection);
        bill.setSupplierRemark(reason.getReason());
        this.billMapper.updateByPrimaryKey(bill);
    }

    //    确认对账结果
    public void confirmedBill(List<Integer> supplierIds, int billID, ReasonRequest reasonBody) {
        Bill bill = this.billMapper.selectByPrimaryKey(billID);
        if (!bill.canConfirmed()) {
            throw new StatusException();
        }
        if (!supplierIds.contains(bill.getSupplierId())) {
            throw new NoPermissionException();
        }
        bill.setStatus(BillStatus.Confirmed);
        bill.setSupplierRemark(reasonBody.getReason());
        this.billMapper.updateByPrimaryKey(bill);

        //        更新发货单状态
//        List<BillDeliver> billDelivers = this.billDeliverMapper.selectByBillID(billID);
//        List<Integer> deliverIDs = billDelivers.stream().map(BillDeliver::getDeliverID).collect(Collectors.toList());
//        this.deliverMapper.UpdateStatusByIDs(deliverIDs, DeliverStatus.Reconciled);
    }

    public BillStatusCountResponse countOrdersByStatus(List<Integer> supplierIds, List<Integer> projectIds) {
        ArrayList<BillStatus> statuses = new ArrayList<>();
        statuses.add(BillStatus.UnConfirmed);
        statuses.add(BillStatus.Confirmed);

        List<BillStatusAndCount> billStatusAndCounts = this.billMapper.countByStatus(supplierIds, projectIds, statuses);

        Map<BillStatus, Integer> orderStatusIntegerMap = ListUtilsKt.mapKV(billStatusAndCounts, (orderStatusAndCount) -> new Pair<>(orderStatusAndCount.getStatus(), orderStatusAndCount.getCount()));

        return new BillStatusCountResponse(
                orderStatusIntegerMap.get(BillStatus.UnConfirmed),
                orderStatusIntegerMap.get(BillStatus.Confirmed)
        );
    }
}
